import Datastore from "lowdb";
import LodashId from "lodash-id";
import FileSync from "lowdb/adapters/FileSync";
import path from "path";
import fs from "fs-extra";

import { getNowDate, getNowDateTime, cmp } from "@/utils/common";
import moment from "moment";

const isDevelopment = process.env.NODE_ENV !== "production";

let db;
function unique(arr,val) {
  const res = new Map();
  return arr.filter(item => !res.has(item[val]) && res.set(item[val], 1))
}
const DB = {
  initDB(storePath) {
    if (!fs.pathExistsSync(storePath)) {
      fs.mkdirpSync(storePath);
    }
    const dbFile = isDevelopment ? "/data-dev.json" : "/data.json";

    const adapter = new FileSync(path.join(storePath, dbFile));

    db = Datastore(adapter);

    db._.mixin(LodashId);

    db.defaults({
      todoList: [
        {
          todo_date: getNowDate(),
          todo_datetime: getNowDateTime(),
          content: "“单击”空处，创建新待办",
          username: "admin"
        },
        {
          todo_date: getNowDate(),
          todo_datetime: getNowDateTime(),
          content: "“双击”待办，销毁待办",
          username: "admin"
        },
        {
          todo_date: getNowDate(),
          todo_datetime: getNowDateTime(),
          content: "“单击”待办，可进行更改或删除",
          username: "admin"
        },
        {
          todo_date: getNowDate(),
          todo_datetime: getNowDateTime(),
          content: "“长按”待办，可拖动排序",
          username: "admin"
        }
      ],
      doneList: [
        {
          done_date: getNowDate(),
          done_datetime: getNowDateTime(),
          todo_date: getNowDate(),
          todo_datetime: getNowDateTime(),
          content: "【重要】记得喝水",
          id: "272aa857-bd53-44fb-b6fc-49d4ef595ade"
        }
      ],
      schedulelist: [
        {
          time: moment()
            .add("1", "m")
            .format("HH:mm"),
          type: "notification",
          content: "喝水"
        }
      ],
      favoritelist: [],
      desktopclassify: [
        {
          pagename: "最近",
          fileDes: []
        }
      ],
      musicList: [],
      settings: {}
    }).write();

    if (!this.has("settings.firstRun")) {
      this.set("settings.firstRun", true);
    }
    if (!this.has("settings.autoChangeWallpaper")) {
      this.set("settings.autoChangeWallpaper", false);
    }
    if (!this.has("favoritelist")) {
      this.set("favoritelist", []);
    }
  },
  has(key) {
    return db
      .read()
      .has(key)
      .value();
  },
  get(key) {
    return db
      .read()
      .get(key)
      .value();
  },
  getColum(key, col) {
    return db
      .get(key)
      .map(col)
      .value();
  },
  set(key, value) {
    return db
      .read()
      .set(key, value)
      .write();
  },
  insert(key, value) {
    return db
      .read()
      .get(key)
      .insert(value)
      .write();
  },
  removeById(key, id) {
    return db
      .read()
      .get(key)
      .removeById(id)
      .write();
  },
  groupby(key, prop) {
    const d = db
      .read()
      .get(key)
      .sortBy(prop)
      .reverse()
      .groupBy(prop)
      .value();
    return d;
  },
  sortschedulelistByTime() {
    const d = db
      .get("schedulelist")
      .sortBy("time")
      .value();
    return d;
  },
  addFavoriteList(url) {
    db.get("favoritelist")
      .push({ url: url })
      .write();
  },
  removeFavoriteList(url) {
    db.get("favoritelist")
      .remove({ url: url })
      .write();
  },
  updateDesktopFile(pname, list) {
    if (pname == "最近") return;
    db.get("desktopclassify")
      .find({ pagename: pname })
      .assign({ fileDes: list })
      .write();
  },
  getFileSortByTime() {
    return Array.prototype.concat
      .apply(
        [],
        db
          .get("desktopclassify")
          .map("fileDes")
          .value()
      )
      .sort((a, b) => {
        return cmp(a.createtime, b.createtime);
      });
  },
  getFileByPageName(pname) {
    return db
      .get("desktopclassify")
      .find({ pagename: pname })
      .value();
  },
  getAllPage() {
    return db
      .get("desktopclassify")
      .map("pagename")
      .value();
  },
  updatepagename(oldp, newp) {
    return db
      .get("desktopclassify")
      .find({ pagename: oldp })
      .assign({ pagename: newp })
      .write();
  },
  deletePage(pagename) {
    db.get("desktopclassify")
      .remove({ pagename: pagename })
      .write();
  },
  getExistPath() {
    return db
      .get("musicList")
      .map("path")
      .value();
  },
  rmDB(tablename) {
    db.unset(tablename).write();
  },
  getcurDayTask(day) {
    return db
      .get("todoList")
      .filter(item => item.todo_date == day)
      .value();
  },
  getcurDayTaskId(day) {
    const rst = db
      .get("todoList")
      .filter(item => item.todo_date == day)
      .map("id")
      .value();
    return rst;
  },
  getTodoByTimeScale(start, end) {
    const list = db
      .get("doneList")
      .concat(db.get("todoList").value())
      .filter(item => {
        return cmp(start, item.todo_date) >= 0 && cmp(item.todo_date, end) >= 0;
      })
      .sort((x, y) => {
        return cmp(x.todo_date - y.todo_date);
      })
      .value();
    return unique(list, "id");
  }
  // getToAndDoneList() {
  //   const todolist = db.get("todoList").value();
  //   const donelist = db.get.get("doneList").value();
  //   var list = [];
  //   return list;
  // }
};

export default DB;
